package com.blb.controller;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.SqlSession;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;
import com.blb.entity.Role;
import com.blb.entity.RoleExample;
import com.blb.entity.User;
import com.blb.entity.UserExample;
import com.blb.entity.UserExample.Criteria;
import com.blb.entity.Userrole;
import com.blb.entity.UserroleExample;
import com.blb.mapper.RoleMapper;
import com.blb.mapper.UserMapper;
import com.blb.mapper.UserroleMapper;
import com.blb.service.UserService;
import com.blb.utils.GetTimeUtils;
import com.blb.utils.LayuiPage;
import com.blb.utils.MybatisUtils;
import com.blb.utils.SessionUtils;
import com.blb.utils.UUIDUtils;
import com.mysql.jdbc.StringUtils;
/**
 * 
 * 用户层
 * @author Administrator
 *
 */
@Controller
@RequestMapping("user")
public class UserController {
	private UserService userService = new UserService();
	private static final String filePath = "D:/file_upload/";
	private static final Class RoleExample = null;
	/**
	 * 用户登录
	 * @param username
	 * @param password
	 * @param model
	 * @return
	 */
	@RequestMapping("login")
	public String login(String username, String password, RedirectAttributes model,HttpSession httpsession) {
			List<User> list;
			try {
				list = userService.login(username);
				if (list.size()==0) {
					model.addFlashAttribute("msg", "用户名不存在");
					return "redirect:/";
				};
				User user=list.get(0);
				if(!user.getPassword().equals(password)){
				
					model.addFlashAttribute("msg", "密码错误");
					return "redirect:/";
				}
				httpsession.setAttribute("user", user);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
				return "index";

	}


	/**
	 * 分页查询
	 * 
	 * @param page
	 * @param limit
	 * @param username
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping("page")
	public LayuiPage PageData(int page, int limit, String username) throws IOException {
		SqlSession session = MybatisUtils.getSession();
		UserMapper userMapper = session.getMapper(UserMapper.class);
		List<User> list = userMapper.page((page - 1) * limit, limit, username);

		UserExample userExample = new UserExample();
		if (!StringUtils.isNullOrEmpty(username)) {
			Criteria criteria = userExample.createCriteria();
			criteria.andUsernameLike(username);
		}
		int count = (int) userMapper.countByExample(userExample);
		LayuiPage layuiPage = new LayuiPage();
		layuiPage.setData(list);
		layuiPage.setCount(count);
		return layuiPage;
	}

	/**
	 * 添加用户
	 * 
	 */
	@ResponseBody
	@RequestMapping("add")
	public String add(User user,@Param("roles")String roles) {
		user.setId(UUIDUtils.getID());
		user.setCreationUser(SessionUtils.getUserName());
		user.setCreationTime(GetTimeUtils.getTime());
		try {
			String msg = userService.addUser(user,roles);
			//添加roles
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";

	}
	/**
	 * 先查询到角色然后再返回到
	 * user_add.jsp页面
	 * @throws IOException 
	 */
	@RequestMapping("addshow")
	public String usershow(Model model) throws IOException{
		SqlSession session = MybatisUtils.getSession();
		RoleMapper mapper = session.getMapper(RoleMapper.class);
		List<Role> list = mapper.selectByExample(null);
		model.addAttribute("roles",list);
		return "user/user_add";
	}
	/**
	 * 先查询到数据然后再返回
	 * user_update.jsp页面
	 * @throws IOException 
	 */
	@RequestMapping("updateshow")
	public String updateshow(User user,Model model) throws IOException{
		SqlSession session = MybatisUtils.getSession();
		//查询全部数组
		RoleMapper mapper = session.getMapper(RoleMapper.class);
		List<Role> list = mapper.selectByExample(null);
		//查询已经勾选的
		UserroleMapper userroleMapper = session.getMapper(UserroleMapper.class);
		UserroleExample userroleExample = new UserroleExample();
		userroleExample.createCriteria().andUserIdEqualTo(user.getId());
		List<Userrole> list2 = userroleMapper.selectByExample(userroleExample);
		
		String chroles="";
		if(!list2.isEmpty()){
			chroles=JSON.toJSON(list2).toString();
		}
		model.addAttribute("roles",list);
		model.addAttribute("chroles",chroles);
		model.addAttribute("user",user);
		return "user/user_update";
		
	}
	

	/**
	 * 修改用户
	 * 
	 * @param user
	 * @param httpSession
	 * @return
	 * @throws SQLException
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping("updateUser")
	public String updateUser(User user,String roles, HttpSession httpSession) {
		User usered;
		try {
			usered = userService.getUserByUserid(user.getId());
			user.setUpdateTime(GetTimeUtils.getTime());
			user.setUpdateUser(SessionUtils.getUserName());
			userService.updateUser(user,roles);
		} catch (SQLException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 添加用户名时查询是否存在
	 */
	@ResponseBody
	@RequestMapping("isExist")
	public String isExist(String username) throws SQLException {
		try {
			User user = userService.getUserByUserName(username);
			if (user != null) {
				return "用户名已存在";
			} else {
				return "";
			}
		} catch (IOException e) {
			e.printStackTrace();
			return e.getMessage();
		}
	}

	/**
	 * 删除用户
	 * 
	 * @param ids
	 * @return
	 */
	@ResponseBody
	@RequestMapping("delete")
	public String delete(@RequestBody String[] ids) {
		System.out.println("1258475");
		try {
			userService.delete(ids);
		} catch (IOException e) {
			e.printStackTrace();
			return e.getMessage();
		}
		return "";
	}

	/**
	 * 修改用户时验证用户名
	 * 
	 * @param username
	 * @param id
	 * @return
	 * @throws SQLException
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping("updateUserIsExist")
	public String IfUpdateServlet(String username, String id) throws SQLException, IOException {
		User user1 = userService.getUserByUserid(id);
		try {
			User user2 = userService.getUserByUserName(username);
			if (user2 != null && !username.equals(user1.getUsername())) {
				return "用户名已存在";
			} else {
				return "";
			}
		} catch (IOException e) {
			e.printStackTrace();
			return e.getMessage();
		}
	}

	/**
	 * 
	 * 注销
	 */
	@RequestMapping("exit")
	public String exit(HttpSession httpSession) {
		httpSession.removeAttribute("User");
		return "redirect:/";
	}

}
